from django.db.models import F
from drf_spectacular.utils import extend_schema
from rest_framework import status
from rest_framework.request import Request
from rest_framework.response import Response

from sentry import audit_log, features
from sentry.api.api_publish_status import ApiPublishStatus
from sentry.api.base import region_silo_endpoint
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.serializers import serialize
from sentry.api.serializers.models.project_key import (
    ProjectKeySerializer,
    ProjectKeySerializerResponse,
)
from sentry.api.serializers.rest_framework import ProjectKeyPostSerializer
from sentry.apidocs.constants import RESPONSE_BAD_REQUEST, RESPONSE_FORBIDDEN
from sentry.apidocs.examples.project_examples import ProjectExamples
from sentry.apidocs.parameters import CursorQueryParam, GlobalParams, ProjectParams
from sentry.apidocs.utils import inline_sentry_response_serializer
from sentry.auth.superuser import is_active_superuser
from sentry.loader.dynamic_sdk_options import get_default_loader_data
from sentry.models.projectkey import ProjectKey, ProjectKeyStatus, UseCase
from sentry.ratelimits.config import RateLimitConfig
from sentry.types.ratelimit import RateLimit, RateLimitCategory


@extend_schema(tags=["Projects"])
@region_silo_endpoint
class ProjectKeysEndpoint(ProjectEndpoint):
    publish_status = {
        "GET": ApiPublishStatus.PUBLIC,
        "POST": ApiPublishStatus.PUBLIC,
    }

    rate_limits = RateLimitConfig(
        limit_overrides={
            "GET": {
                RateLimitCategory.IP: RateLimit(limit=40, window=1),
                RateLimitCategory.USER: RateLimit(limit=40, window=1),
                RateLimitCategory.ORGANIZATION: RateLimit(limit=40, window=1),
            },
            "POST": {
                RateLimitCategory.IP: RateLimit(limit=40, window=1),
                RateLimitCategory.USER: RateLimit(limit=40, window=1),
                RateLimitCategory.ORGANIZATION: RateLimit(limit=40, window=1),
            },
        },
    )

    @extend_schema(
        operation_id="List a Project's Client Keys",
        parameters=[
            GlobalParams.ORG_ID_OR_SLUG,
            GlobalParams.PROJECT_ID_OR_SLUG,
            CursorQueryParam,
            ProjectParams.STATUS,
        ],
        responses={
            200: inline_sentry_response_serializer(
                "ListClientKeysResponse", list[ProjectKeySerializerResponse]
            ),
            400: RESPONSE_BAD_REQUEST,
            403: RESPONSE_FORBIDDEN,
        },
        examples=ProjectExamples.LIST_CLIENT_KEYS,
    )
    def get(self, request: Request, project) -> Response:
        """
        Return a list of client keys bound to a project.
        """
        queryset = ProjectKey.objects.for_request(request).filter(
            project=project, roles=F("roles").bitor(ProjectKey.roles.store)
        )
        status = request.GET.get("status")
        if status == "active":
            queryset = queryset.filter(status=ProjectKeyStatus.ACTIVE)
        elif status == "inactive":
            queryset = queryset.filter(status=ProjectKeyStatus.INACTIVE)
        elif status:
            queryset = queryset.none()

        return self.paginate(
            request=request,
            queryset=queryset,
            order_by="-id",
            default_per_page=10,
            on_results=lambda x: serialize(x, request.user, request=request),
        )

    @extend_schema(
        operation_id="Create a New Client Key",
        parameters=[
            GlobalParams.ORG_ID_OR_SLUG,
            GlobalParams.PROJECT_ID_OR_SLUG,
        ],
        request=ProjectKeyPostSerializer,
        responses={
            201: ProjectKeySerializer,
            400: RESPONSE_BAD_REQUEST,
            403: RESPONSE_FORBIDDEN,
        },
        examples=ProjectExamples.CLIENT_KEY_RESPONSE,
    )
    def post(self, request: Request, project) -> Response:
        """
        Create a new client key bound to a project.  The key's secret and public key
        are generated by the server.
        """
        serializer = ProjectKeyPostSerializer(data=request.data)

        if not serializer.is_valid():
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        result = serializer.validated_data

        rate_limit_count = None
        rate_limit_window = None

        if features.has("projects:rate-limits", project):
            ratelimit = result.get("rateLimit", -1)
            if ratelimit != -1 and (ratelimit["count"] and ratelimit["window"]):
                rate_limit_count = result["rateLimit"]["count"]
                rate_limit_window = result["rateLimit"]["window"]

        if is_active_superuser(request):
            use_case = result.get("useCase", UseCase.USER.value)
        else:
            use_case = UseCase.USER.value

        key = ProjectKey.objects.create(
            project=project,
            label=result.get("name"),
            public_key=result.get("public"),
            secret_key=result.get("secret"),
            rate_limit_count=rate_limit_count,
            rate_limit_window=rate_limit_window,
            data=get_default_loader_data(project),
            use_case=use_case,
        )

        self.create_audit_entry(
            request=request,
            organization=project.organization,
            target_object=key.id,
            event=audit_log.get_event_id("PROJECTKEY_ADD"),
            data=key.get_audit_log_data(),
        )

        return Response(serialize(key, request.user, request=request), status=201)
